//
//  OAuthViewController.swift
//  SinaWeibo
//
//  Created by mac on 15/12/15.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
class OAuthViewController: UIViewController{
    //定义 webView 属性
 let webView = UIWebView()
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }

    
    @objc private func defaultAccount() {
        
        let jsString = "document.getElementById('userId').value = '15335922705' ,document.getElementById('passwd').value = 'yulin19920423' "
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }

    override func loadView() {
        view = webView
        //设置代理
        webView.delegate = self
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        //加载授权页面
        loadOauthPage()
        setNavBar()
        
        
    }
    //加载授权页面
    
    private func loadOauthPage(){
        
        //1.urlString
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)
        webView.loadRequest(NSURLRequest(URL: url!))
    

    }
    //设置导航条
    private func setNavBar(){
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "defaultAccount")
    }

}




extension OAuthViewController: UIWebViewDelegate {
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
        
        
    }
    




        func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
            print(request.URL)
            
            
            //需要根据请求的url 去屏蔽不希望加载的页面
            guard let urlString = request.URL?.absoluteString else {
                return false
            }
            
            if urlString.hasPrefix("https://api.weibo.com/") {
                //希望加载的页面
                return true
            }
            
            if !urlString.hasPrefix("http://www.baidu.com") {
                //一定不是请求成功后的回调  同样也不会是 我们希望加载的页面
                return false
            }
            
            //程序走到这里 一定是请求成功后的回调
            print(urlString)
            //解析字符串获取code码
            // query 获取到url中 参数部分 键值
            let query = request.URL?.query
            if let q = query {
                //字符串截取操作
                let codeStr = "code="
                let code = q.substringFromIndex(codeStr.endIndex)
                //加载用户token
                loadAccessToken(code)
            }
            return true
    }
    private func loadAccessToken(code:String) {
        UserAccountViewModel().loadAccessToken(code) { (isSuccess) -> () in
            if isSuccess {
                print("登陆成功")
                //动画结束的时候 发出 页面切换的通知
                
                //通知是同步的还是异步的?
                //通知是同步的
                
                
                //这个方法是控制器dismiss掉 但是并不会立即被回收
                //modla出来的页面 注意回收 需要手动close
                self.dismissViewControllerAnimated(false, completion: { () -> Void in
                    //等待 被modal出来的页面 彻底被回收是 再发出页面切换的通知
                    NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootVCNotification, object: "Welcome")
                    
                    print("come here")
                })
            } else {
                print("登陆失败")
            }
        }
        
        
        
    }
    
    
        }


